/**
 *
 * 弹出框选择图片，
 *  作用：上传一张图片，添加对应的描述，进行添加
 *  备注：非纯ui组件，携有部分功能与基础逻辑
 */

import React from "react";
import {Modal,Upload,Icon,Input,message} from 'antd';
import Relay from "react-relay";
import DelQiniuFileMutation from "../mutation/DelQiniuFileMutation" // 删除图片

import {Button} from "fly";

import classnames from 'classnames';
const confirm = Modal.confirm;

export default class A extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible:false,
            text:"",
            fileList:[],  //当前图片文件
            imgSrc:"",  //当前上传图片的url
            alarm:false,  // 格式提示文本

            showLoading:false,   //上传进度条是否显示
            progress:0 ,   //上传的进度

            left:0,  //拖动x
            top:0,   //拖动Y

            ImgScale:100,
            ok_loading:false,  //btn loading
            isPush:true,  //上传中途取消时，是否push
            isOk:false   // 最终确认的状态
        };

        this.onOk = this.onOk.bind(this);
        this.onCancel = this.onCancel.bind(this);
        this.updataFile = this.updataFile.bind(this);
        this.onFilChange = this.onFilChange.bind(this);
        this.picRemove = this.picRemove.bind(this);

        // 拖动事件
        this.handleMouseDown = this.handleMouseDown.bind(this);
        this.handleMouseUp = this.handleMouseUp.bind(this);

        // 方法缩小方法
        this.ImgScale = this.ImgScale.bind(this);
    }

    //验证图片promise
    testImgPromise = (result)=>{
        return new Promise((resolve,reject)=>{
            // 获取当前文件base码;
            const {width,height} = this.props.limit;
            let Img = new Image(); Img.src = result;
            Img.onload = ()=>{
                const w = Img.width, h = Img.height;
                if( width <= w || height <= h){
                    // 格式无误，执行下一步操作
                    resolve();
                }else{
                    reject();
                }
            };
            Img.onerror = ()=>{
                reject();
            }
        })
    };

    getBase64(img, callback) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    }

    ImgCatch(){
        // 小于了规定的尺寸
        this.setState({
            alarm:true
        },()=>{message.error("请仔细阅读图片上传规则");});
    }

    //  预览图片放大缩小
    ImgScale(e){
        if(e.deltaY >= 100){
            this.setState({
                ImgScale:this.state.ImgScale + 3
            })
        }else if(e.deltaY <= 100){
            this.setState({
                ImgScale:this.state.ImgScale - 3
            })
        }
    }


    //asdsdasds
    onOk(){
        const file = this.state.fileList,
               ok = this.state.isOk;

        if(file.length!==0){

            // 格式验证
            const text  =  this.state.text,
                   regu = "^[ ]+$",
                   re = new RegExp(regu);

            if(re.test(text)){  message.info("请填写合法字符");  return; }

            // 是否为上传完成
            if(file[0].status !== "done" || !ok)  {
                return;
            }

            const obj = {file:file[0],text:this.state.text};
            this.props.addFileImg(obj);

            this.clear();  //清空状态


        }else{
            message.error("请上传图片");
        }
    }


    picRemove(callback){
        //下列固定为0，因为list最多只能上传一个，固0
        const name = this.state.fileList[0].response.key;

        if(!name){ return }

        Relay.Store.commitUpdate(
            new DelQiniuFileMutation({
                fileKey: name
            }),
            {
                onFailure: () => {
                    message.error("网络请求失败")
                },
                onSuccess: (response) => {
                    let errorCode = response.delQiniuFile.delQiniuFile.errorCode;
                    if (errorCode == 0) {
                        callback && callback()
                    }else{
                        message.error("服务器错误，请联系管理员")
                    }
                }
            }
        )
    }

    //asd
    // 清空
    clear(){
        this.setState({
            visible:false,
            text:"",
            imgSrc:"",
            fileList:[],
            left:0,
            top:0,
            alarm:false,
            showLoading:false
        });
        this.handleMouseUp();
    }


    onCancel(){
        // 删除图片
       if( this.state.fileList.length !== 0) {
           if(this.state.fileList[0].status === "uploading"){
               message.warning("当前图片正在上传中");
               return;
           }else if(this.state.fileList[0].status === "done"){
               this.picRemove();
           }
           this.clear(); //清空状态
       }else{
           this.clear(); //清空状态
       }
    }

    updataFile(file,index,id){
        const date = new Date().getTime();
        return {file:file,token:this.props.token,key:`PackStep_${date}`}
    }

    onFilChange({file,fileList,event}){
        // 无论哪种情况都把fileList返回给当前状态
        !(function () {
            this.state.fileList = fileList;
            this.setState({fileList:this.state.fileList});
        }.bind(this))();

        // 在uploading 当中显示进度条
        if(file.status === "uploading"){
            if(event){
                if(this.state.visible === true){
                    this.setState({
                        showLoading:true
                    },()=>{
                        // 开始 Progress
                        const progress = (event.loaded/event.total)*100;
                        //loaded
                        this.setState({progress})
                    })
                }else{
                    this.clear()
                }
            }
        }

        // 上传成功
        if(file.status === "done"){
            // 读取文件bse64回调
            this.getBase64(file.originFileObj,(result)=>{
                //验证图片格式（宽高） [异步]
                this.testImgPromise(result).then(()=>{
                    /// 只能在窗口打开的情况下进行.
                    if(this.state.isPush === true){
                        this.setState({
                            imgSrc:result,
                            showLoading:false,
                            alarm:false,
                            isOk:true
                        });
                    }else{
                        this.clear();
                        this.setState({ isOk:false })
                    }
                }).catch(()=>{
                    this.ImgCatch();
                    this.setState({
                        showLoading:false,
                        fileList:[],
                        isOk:false
                    })
                })
            });
        }

        //上传失败
        if(file.status === "error"){
            message.error("上传图片失败，请重试");
        }

        // 删除图片
        if(file.status === "removed"){
            console.log("删除图片");
        }
    }

   // 拖动功能
    handleMouseDown(event) {
        let e = event || window.event,
        disX = e.clientX - event.target.offsetLeft,
        disY = e.clientY - event.target.offsetTop;

        document.onmousemove = (event)=>{
            let e = event || window.event;
            this.setState({
                left:(e.clientX - disX),
                top:(e.clientY - disY)
            })
        }
    }

    handleMouseUp(){
        document.onmousemove = null;
        document.onmouseup = null;
    }

    handleTextChange = (e)=>{
        this.setState({text:e.target.value})
        if( this.state.text.length >= this.props.TextProps.maxLength ){
            const t = this.state.text;
            this.setState({text:t.slice(0,t.length-1)})
        }
    };

    render() {
        const {uploadPlugin,TextProps} = this.props;
        const {fileList,imgSrc,showLoading,progress,left,top,text,alarm,ImgScale,ok_loading,cancel_loading} = this.state;
        return(
            <Modal
                className="packagSteps_AddImgModal"
                visible={this.state.visible}
                title="上传图片"
                maskClosable={false}
                footer={null}
                onCancel={this.onCancel}
            >
                <Upload
                    {...uploadPlugin}
                    fileList={fileList}
                    disabled={fileList.length !== 0}
                    data={this.updataFile}
                    onChange={this.onFilChange}
                    onRemove={this.picRemove}
                    showUploadList={false}
                >
                        {
                            fileList.length !== 0 ?
                                <img src={imgSrc}
                                     draggable="false"
                                     className="packagSteps_update_preview"
                                     style={{left,top,width:`${ImgScale}%`}}
                                     onMouseDown={this.handleMouseDown}
                                     onMouseUp={this.handleMouseUp}
                                     onMouseLeave={this.handleMouseUp}
                                /> :
                                <div className="packagSteps_AddImgModal_middleAlarm">
                                    <Icon type="plus" /> 添加图片
                                </div>
                        }
                    {/*</div>*/}
                    {/*进度条展示*/}
                    {
                       showLoading &&
                        <div>
                            <p className="packagSteps_AddImgModal_progress">
                                <i className="packagSteps_AddImgModal_progress_color" style={{width:`${progress}%`}}></i>
                            </p>
                            <p className="packagSteps_AddImgModal_percentage">
                                { parseFloat(progress).toFixed(0) } %
                                {
                                    progress === 100 &&
                                    <span> 上传完成，请稍等... </span>
                                }
                            </p>
                        </div>
                    }
                </Upload>

                <div>
                    <Input type="textarea"
                           value={text}
                           onChange={this.handleTextChange}
                           {...TextProps}
                            maxLength="50"
                    />
                </div>

                <footer>
                    <p className={classnames({"packagSteps_AddImgModal_alarm":true,"hide":!alarm})}>
                        请您上传大于500*500像素、其大小不超过8M的，BMP、JPEG、JPG、GIF、PNG格式的图片。
                    </p>

                    <div className="packagSteps_AddImgModal_choose">
                        <Button type="blank"  onClick={this.onCancel} loading={cancel_loading}>
                            取消
                        </Button>
                        <Button type="blank"  onClick={this.onOk} loading={ok_loading}>
                            确定
                        </Button>
                    </div>
                </footer>
            </Modal>
        )
    }

}